package striveen.util.used.loading;

import striveen.util.used.R;
import striveen.util.used.log.Log;
import android.content.Context;

public class LoadingDataDialogManager {
	private final String TAG = LoadingDataDialogManager.class.getSimpleName();
	private int index;
	private LoadingDataDialog progressDialog;
	Context context;
	Context context_Last;
	private boolean isCancelable=true;
	private LoadingDataDialogManager(Context context, String loadingMsg) {
		this.index = 0;
		this.context = context;
		if (!this.context.equals(context_Last)) {
			context_Last = this.context;
			index = 1;
			dismiss();
		}
		this.progressDialog = new LoadingDataDialog(context);

		if (loadingMsg == null) {
			this.progressDialog.setMessage(context
					.getString(R.string.text_loadingdata));
		} else {
			this.progressDialog.setMessage(loadingMsg);
		}

		this.progressDialog.setCancelable(isCancelable);
		this.progressDialog.setCanceledOnTouchOutside(false);
	}

	public boolean isCancelable() {
		return isCancelable;
	}

	public void setIsCancelable(boolean isCancelable) {
		this.isCancelable = isCancelable;
	}

	public static LoadingDataDialogManager init(Context context) {
		return new LoadingDataDialogManager(context, null);
	}

	public static LoadingDataDialogManager init(Context context,
			String loadingMsg) {
		return new LoadingDataDialogManager(context, loadingMsg);
	}

	public static LoadingDataDialogManager init(Context context,
			int resIdLoadingMsg) {
		return new LoadingDataDialogManager(context, context.getResources()
				.getString(resIdLoadingMsg));
	}

	public void destroy() {
		if (this.progressDialog != null) {
			this.progressDialog.dismiss();
			this.progressDialog = null;
		}
	}

	public void show() {
		if (this.index == 0) {
			if (this.progressDialog != null)
				this.progressDialog.show();
			else {
				Log.w(this.TAG, "progressDialog not init");
			}
		}
		this.index += 1;
	}

	public void update(String msg) {
		if (this.progressDialog != null)
			this.progressDialog.setMessage(msg);
		else
			Log.w(this.TAG, "progressDialog not init");
	}

	public void dismiss() {
		if (this.index <= 1) {
			if (this.progressDialog != null)
				this.progressDialog.hide();
			else {
				Log.w(this.TAG, "progressDialog not init");
			}
			this.index = 0;
		} else {
			this.index -= 1;
		}
	}
}
